package servlets;

import java.io.IOException;



import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import server.ForumAPIService;
import server.controller.WebAdapter;

import database.DBHandler;
import database.DatabaseStub;
import forum.Post;

/**
 * Servlet implementation class ViewThreads
 */
//@WebServlet("/ViewThreads")
public class ViewThreads extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ViewThreads() {
        super();
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init() throws ServletException {
		super.init();
		
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		super.destroy();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected synchronized void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("viewTreads. doGet");
		
		// init session of request
		HttpSession session = request.getSession();
		
		Boolean isLoggedIn = (Boolean) session.getAttribute("isLoggedIn");

		if (isLoggedIn != null && isLoggedIn.booleanValue()) {
			
			int forumID = ((Integer)session.getAttribute("forumID")).intValue();
			ForumAPIService db = WebAdapter.getInstance();

			// get all threads
			List<forum.Thread> allThreads = db.getThreads(forumID);
			
			// set the returned collection in the request
			request.setAttribute("threads", allThreads);
			

			// get the request dispatcher
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/threadsPage.jsp");

			// forward to the jsp file to display the book list
			dispatcher.forward(request, response);
		}
		else {//not logged in
			
			request.setAttribute("errorMsg", "Please Log In");
			String addr = "http://"+request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
			
			request.setAttribute("errorLink", addr);
			// get the request dispatcher
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/jsp/Error.jsp");

			// forward to the jsp file to display the book list
			dispatcher.forward(request, response);
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected synchronized void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("viewTreads. doPost");
		this.doGet(request, response);
	}

}
